package com.ruoyi.web.service;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 人脸核身验证
 */
@Slf4j
@Service
public class RealNameService {


    private final static String APPID = "IDAxUZWx";
    private final static String SECRET = "5TkdFxKy9qzC8GWVdOYd6flcp56Rtx4BXwKunUavoY01XMZ6GvC23j6e05DJRWcg";


    /**
     * 获取accessToken
     *
     * @return
     */
    private static String getAccessToken() {
        String url = "https://kyc1.qcloud.com/api/oauth2/access_token?appId=" + APPID + "&secret=" + SECRET + "&grant_type=client_credential&version=1.0.0";
        try {
            HttpRequest request = HttpRequest.get(url);
            HttpResponse response = request.execute();
            log.info("腾讯云:getAccessToken:{}", response.body());
            JSONObject jsonObject = JSONObject.parseObject(response.body());
            if (StringUtils.equals(jsonObject.getString("code"), Constants.SUCCESS)) {
                return jsonObject.getString("access_token");
            }
        } catch (Exception e) {
            log.info("获取腾讯云getAccessToken失败：{}", e.getMessage());
        }
        return null;
    }

    /**
     * 获取signTicket
     *
     * @return
     */
    private static String getSignTicket() {
        String url = "https://kyc1.qcloud.com/api/oauth2/api_ticket";
        String token = getAccessToken();
        if (StringUtils.isBlank(token)) {
            return null;
        }
        String params = "?appId=" + APPID + "&access_token=" + token + "&type=SIGN&version=1.0.0";
        try {
            HttpRequest request = HttpRequest.get(url + params);
            HttpResponse response = request.execute();
            log.info("腾讯云:getSignTicket:{}", response.body());
            JSONObject jsonObject = JSONObject.parseObject(response.body());
            if (StringUtils.equals(jsonObject.getString("code"), Constants.SUCCESS)) {
                JSONArray tickets = jsonObject.getJSONArray("tickets");
                String ticket = tickets.getString(0);
                return JSONObject.parseObject(ticket).getString("value");
            }
        } catch (Exception e) {
            log.info("获取腾讯云getSignTicket失败：{}", e.getMessage());
        }
        return null;
    }

    /**
     * 获取人脸验证的faceId
     *
     * @param cardName 身份证姓名
     * @param card     身份证号
     * @param userID   用户ID
     * @param orderNo  订单ID
     * @return
     */
    public static HashMap<String, String> checkName(String cardName, String card, String userID, String orderNo,String nonce) {
        HashMap<String, String> hashMap = new HashMap<>();
        String url = "https://kyc1.qcloud.com/api/server/getAdvFaceId?orderNo=" + orderNo;
        String ticket = getSignTicket();
        if (StringUtils.isBlank(ticket)) {
            return hashMap;
        }
        String version = "1.0.0";
        ArrayList<String> values = new ArrayList<>();
        values.add(APPID);
        values.add(userID);
        values.add(nonce);
        values.add(version);
        String sign = sign(values, ticket);
        Map<String, Object> params = new HashMap<>();
        params.put("appId", APPID);
        params.put("orderNo", orderNo);
        params.put("name", cardName);
        params.put("idNo", card);
        params.put("userId", userID);
        params.put("version", version);
        params.put("sign", sign);
        params.put("nonce", nonce);
        try {
            HttpRequest request = HttpRequest.post(url);
            request.header("content_type", "Content-Type: application/json");
            request.body(JSONObject.toJSONString(params));
            HttpResponse response = request.execute();
            log.info("response:{}", response.body());
            JSONObject jsonObject = JSONObject.parseObject(response.body());
            if (StringUtils.equals(jsonObject.getString("code"), Constants.SUCCESS)) {
                JSONObject resultObject = jsonObject.getJSONObject("result");
                hashMap.put("openApiSign", sign);
                hashMap.put("faceId", resultObject.getString("faceId"));
            }
        } catch (Exception e) {
            log.info("获取腾讯云人脸核验失败：{}", e.getMessage());
        }
        return hashMap;
    }


    public static String sign(List<String> values, String ticket) { //values传ticket外的其他参数
        if (values == null) {
            throw new NullPointerException("values is null");
        }
        values.removeAll(Collections.singleton(null));// remove null
        values.add(ticket); java.util.Collections.sort(values);
        StringBuilder sb = new StringBuilder();
        for (String s : values) { sb.append(s);
        }
        return Hashing.sha1().hashString(sb,
            Charsets.UTF_8).toString().toUpperCase();
    }
}
